package com.hzw.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.hzw.util.DbUtil;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * 数据源配置
 */
@Configuration
// 扫描 Mapper 接口并容器管理
@MapperScan(basePackages = DatasourceConfig.PACKAGE, sqlSessionFactoryRef = "sqlSessionFactory")
public class DatasourceConfig {
    // mapper扫描
    static final String PACKAGE = "com.hzw.mapper";
    static final String MAPPER_LOCATION = "classpath:mapper/*.xml";

    @Value("${ds.basic.datasource.url}")
    private String urlBasic;
    @Value("${ds.basic.datasource.username}")
    private String userBasic;
    @Value("${ds.basic.datasource.password}")
    private String passwordBasic;
    @Value("${ds.basic.datasource.driver-class-name}")
    private String driverClassBasic;

    @Value("${ds.base.datasource.url}")
    private String urlBase;
    @Value("${ds.base.datasource.username}")
    private String userBase;
    @Value("${ds.base.datasource.password}")
    private String passwordBase;
    @Value("${ds.base.datasource.driver-class-name}")
    private String driverClassBase;

    //@Value("${ds.article.datasource.url}")
    //private String urlArticle;
    //@Value("${ds.article.datasource.username}")
    //private String userArticle;
    //@Value("${ds.article.datasource.password}")
    //private String passwordArticle;
    //@Value("${ds.article.datasource.driver-class-name}")
    //private String driverClassArticle;
    //
    //@Value("${ds.friend.datasource.url}")
    //private String urlFriend;
    //@Value("${ds.friend.datasource.username}")
    //private String userFriend;
    //@Value("${ds.friend.datasource.password}")
    //private String passwordFriend;
    //@Value("${ds.friend.datasource.driver-class-name}")
    //private String driverClassFriend;

    @Value("${ds.datasource.max_active}")
    private Integer maxActive;
    @Value("${ds.datasource.min_idle}")
    private Integer minIdle;
    @Value("${ds.datasource.initial_size}")
    private Integer initialSize;
    @Value("${ds.datasource.max_wait}")
    private Long maxWait;
    @Value("${ds.datasource.time_between_eviction_runs_millis}")
    private Long timeBetweenEvictionRunsMillis;
    @Value("${ds.datasource.min_evictable_idle_time_millis}")
    private Long minEvictableIdleTimeMillis;
    @Value("${ds.datasource.test_while_idle}")
    private Boolean testWhileIdle;
    @Value("${ds.datasource.test_while_idle}")
    private Boolean testOnBorrow;
    @Value("${ds.datasource.test_on_borrow}")
    private Boolean testOnReturn;

    @Bean(name = "dynamicDataSource")
    @Primary
    public DynamicDataSource dynamicDataSource() {
        DynamicDataSource dynamicDataSource = DynamicDataSource.getInstance();

        // basic数据源
        DruidDataSource dataSourceBasic = initDataSource(driverClassBasic,urlBasic,userBasic,passwordBasic);
        // base数据源
        DruidDataSource dataSourceBase = initDataSource(driverClassBase,urlBase,userBase,passwordBase);
        // article数据源
        //DruidDataSource dataSourceArticle = initDataSource(driverClassArticle,urlArticle,userArticle,passwordArticle);
        //// friend数据源
        //DruidDataSource dataSourceFriend = initDataSource(driverClassFriend,urlFriend,userFriend,passwordFriend);

        Map<Object,Object> map = new HashMap<>();
        map.put(DbUtil.DB_BASIC, dataSourceBasic);
        map.put(DbUtil.DB_BASE, dataSourceBase);
        //map.put(DbUtil.DB_ARTICLE, dataSourceArticle);
        //map.put(DbUtil.DB_FRIEND, dataSourceFriend);

        dynamicDataSource.setTargetDataSources(map);
        // 默认数据源
        dynamicDataSource.setDefaultTargetDataSource(dataSourceBasic);
        return dynamicDataSource;
    }

    /**
     * 初始数据源
     * @param driver    驱动
     * @param url       数据库连接
     * @param username  用户名
     * @param password  密码
     * @return
     */
    public DruidDataSource initDataSource(String driver,String url,String username,String password){
        //jdbc配置
        DruidDataSource rdataSource = new DruidDataSource();
        rdataSource.setDriverClassName(driver);
        rdataSource.setUrl(url);
        rdataSource.setUsername(username);
        rdataSource.setPassword(password);
        setPool(rdataSource);
        return rdataSource;
    }

    /**
     * 连接池配置
     * @param rdataSource
     */
    private void setPool(DruidDataSource rdataSource){
        //连接池配置
        rdataSource.setMaxActive(maxActive);
        rdataSource.setMinIdle(minIdle);
        rdataSource.setInitialSize(initialSize);
        rdataSource.setMaxWait(maxWait);
        rdataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        rdataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        rdataSource.setTestWhileIdle(testWhileIdle);
        rdataSource.setTestOnBorrow(testOnBorrow);
        rdataSource.setTestOnReturn(testOnReturn);
        rdataSource.setValidationQuery("SELECT 'x'");
        rdataSource.setPoolPreparedStatements(true);
        rdataSource.setMaxPoolPreparedStatementPerConnectionSize(20);
        try {
            rdataSource.setFilters("stat");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Bean(name = "transactionManager")
    @Primary
    public DataSourceTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dynamicDataSource());
    }

    @Bean(name = "sqlSessionFactory")
    @Primary
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dynamicDataSource") DataSource dynamicDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dynamicDataSource);
        sessionFactory.setTypeAliasesPackage("com.hzw.model");
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(DatasourceConfig.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }


    @Bean
    public ServletRegistrationBean druidServlet() {
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
        servletRegistrationBean.setServlet(new StatViewServlet());
        servletRegistrationBean.addUrlMappings("/druid/*");
        Map<String, String> initParameters = new HashMap<String, String>();
        // 用户名
        initParameters.put("loginUsername", "admin");
        // 密码
        initParameters.put("loginPassword", "admin");
        // 禁用HTML页面上的“Reset All”功能
        initParameters.put("resetEnable", "false");
        // IP白名单 (没有配置或者为空，则允许所有访问)
        initParameters.put("allow", "");
        servletRegistrationBean.setInitParameters(initParameters);
        return servletRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }

}